from captcha.fields import CaptchaTextInput, CaptchaField
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
from django.template.context_processors import request
from .models import CustomUser
#
# from .models import CustomUser
# from captcha.fields import CaptchaField,CaptchaTextInput


class LoginForm(forms.Form):
    username = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control'})
    )
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'form-control'})
    )

    def clean_username(self):
        """仅保证用户名存在即可"""
        username = self.cleaned_data['username']
        if not CustomUser.objects.filter(username=username).exists():
            raise forms.ValidationError('用户名不存在')
        return username

    def clean(self):
        """联合校验：用户名+密码是否正确"""
        cleaned = super().clean()
        username = cleaned.get('username')
        password = cleaned.get('password')

        # 如果用户名字段本身就没通过，不往下走
        if username and password:
            user = CustomUser.objects.filter(username=username).first()
            if user and not user.check_password(password):
                self.add_error('password', '密码错误')
            elif not user:
                # 理论上不会进来，因为 clean_username 已拦截
                self.add_error('username', '用户名不存在')
        return cleaned

class RegisterForm(forms.ModelForm):
    password2 = forms.CharField(label="确认密码",widget=forms.PasswordInput(attrs={'class':'form-control'}))
    # captcha = ChaptchaField(label="验证码",
    #                     error_messages={"required": "验证码不能为空"},widget=CaptchaText
    # )
    captcha = CaptchaField(label="验证码",
                           error_messages={"required": "验证码不能为空"},widget=CaptchaTextInput(attrs={'class':'form-control'}))

    class Meta:
        model = CustomUser
        fields = ['username','password']
        widgets = {

            'username': forms.TextInput(attrs={'class':'form-control'}),
            'password': forms.PasswordInput(attrs={'class':'form-control'}),
        }

    def clean_email(self):
        email = self.cleaned_data['email']
        if CustomUser.objects.filter(email=email).exists():
            raise forms.ValidationError('邮箱已经存在')
        # 必须返回清洗后的值，否则字段会变成 None
        return email
    def clean_username(self):
        username = self.cleaned_data['username']
        if CustomUser.objects.filter(username=username).exists():
            raise forms.ValidationError('用户名已经存在')
        # 必须返回清洗后的值，否则字段会变成 None
        return username


    def clean_password(self):
        password = self.cleaned_data['password']
        if len(password) < 3:
            raise forms.ValidationError('密码长度需要大于3')
        return password

    def clean_password2(self):
        password = self.cleaned_data.get('password')
        password2 = self.cleaned_data.get('password2')
        if password and password2 and password != password2:
            raise forms.ValidationError('两次输入的密码不一致')
        return password2

    def save(self, commit=True):
        # 确保密码以哈希形式保存
        user = super().save(commit=False)
        raw_password = self.cleaned_data.get('password')
        if raw_password:
            user.set_password(raw_password)
        if commit:
            user.save()
        return user